package cn.always.xiajia.framework.web.core.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import cn.always.xiajia.framework.common.util.ExtServletUtil;

/**
 * Request Body 缓存 Wrapper
 * 
 * @author xgj
 *
 */
public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {

	/**
	 * 缓存的内容
	 */
	private final byte[] body;

	public CacheRequestBodyWrapper(HttpServletRequest request) {
		super(request);
		body = ExtServletUtil.getBodyBytes(request);
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
		// 返回 ServletInputStream
		return new ServletInputStream() {

			@Override
			public int read() {
				return inputStream.read();
			}

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {
			}

			@Override
			public int available() {
				return body.length;
			}

		};
	}

}
